package com.xsm.ppsecret.ui.log;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.xsm.ppsecret.R;
import com.xsm.ppsecret.adapter.BaseRecyclerAdapter;
import com.xsm.ppsecret.adapter.LogAdapter;
import com.xsm.ppsecret.model.LogEntry;
import com.xsm.ppsecret.sql.DBHelper;
import com.xsm.ppsecret.sql.DataContracts;
import com.xsm.ppsecret.util.JsonUtils;
import com.xsm.ppsecret.widgets.DeleteDialog;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Single;
import io.reactivex.SingleEmitter;
import io.reactivex.SingleObserver;
import io.reactivex.SingleOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class LogActivity extends AppCompatActivity implements BaseRecyclerAdapter.OnChildClickListener, BaseRecyclerAdapter.OnLongChildClickListener, DeleteDialog.DeleteListener {

    public static final int ADD_LOG = 8023;
    private static final int LOAD_OK = 613;
    @BindView(R.id.menu_normal_title)
    TextView menuTitle;
    @BindView(R.id.menu_normal_action)
    TextView menuAction;
    @BindView(R.id.log_recycler)
    RecyclerView mRecyclerView;
    private List<LogEntry> mList;
//    private MyHandler mHandler = new MyHandler(this);
    private LogAdapter mAdapter;
    private Disposable mDisposable;
    private Disposable mDeleteDisposable;
    private Disposable mLoadDisposable;
    private int mPosition;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_log);
        ButterKnife.bind(this);
        menuTitle.setText("私密日志");
        menuAction.setText("添加");
        mList = new ArrayList<>();

        mAdapter = new LogAdapter(this, mList);
        mAdapter.setOnChildClickListener(this);
        mAdapter.setOnLongChildClickListener(this);
        mRecyclerView.setAdapter(mAdapter);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));

        loadData();

    }

    private void loadData() {
        Single.create(new SingleOnSubscribe<ArrayList<LogEntry>>() {
            @Override
            public void subscribe(SingleEmitter<ArrayList<LogEntry>> e) throws Exception {
                ArrayList<LogEntry> logEntries = handleData();
                e.onSuccess(logEntries);
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SingleObserver<ArrayList<LogEntry>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        mDisposable = d;
                    }

                    @Override
                    public void onSuccess(ArrayList<LogEntry> value) {
                        if (value != null && value.size() > 0) {
                            mList.clear();
                            mList.addAll(value);
                            mAdapter.notifyDataSetChanged();
                        } else {
                            mList.clear();
                            mAdapter.notifyDataSetChanged();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Toast.makeText(LogActivity.this, "加载出错", Toast.LENGTH_SHORT).show();
                    }
                });
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mDisposable != null && !mDisposable.isDisposed()) {
            mDisposable.dispose();
        }
        if (mDeleteDisposable != null && !mDeleteDisposable.isDisposed()) {
            mDeleteDisposable.dispose();
        }
        if (mLoadDisposable != null && !mLoadDisposable.isDisposed()) {
            mLoadDisposable.dispose();
        }
    }

    private ArrayList<LogEntry> handleData() {
        ArrayList<LogEntry> list = null;
        DBHelper dbHelper = new DBHelper(this);
        SQLiteDatabase database = dbHelper.getWritableDatabase();
        Cursor cursor = database.query(DataContracts.LOGS.TABLE_NAME,
                null,
                null,
                null,
                null,
                null,
                "_id desc",
                null
        );
        if (cursor != null) {
            list = new ArrayList<>();
            while (cursor.moveToNext()) {
                int index = cursor.getColumnIndex(DataContracts.LOGS._ID);
                int id = cursor.getInt(index);
                int json = cursor.getColumnIndex(DataContracts.LOGS.JSON);
                String str = cursor.getString(json);
                LogEntry logEntry = new LogEntry(id, str);
                list.add(logEntry);
            }
            cursor.close();
        }
        return list;
    }

    @OnClick(R.id.menu_normal_action) void add() {
        startActivityForResult(new Intent(this, LogEditActivity.class), ADD_LOG);
    }

    @OnClick(R.id.menu_normal_back) void back() {
        finish();
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == ADD_LOG) {
            if (resultCode == RESULT_OK) {
                loadData();
            }
        }

    }

    @Override
    public void onChildClick(RecyclerView parent, View view, int position) {
        LogEntry logEntry = mList.get(position);
        Intent intent = new Intent(this, LogEditActivity.class);
        intent.putExtra("json", JsonUtils.getInstance().serialize(logEntry));
        startActivityForResult(intent, ADD_LOG);
    }

    @Override
    public void onLongChildClick(RecyclerView parent, View view, int position) {
        mPosition = position;
        DeleteDialog dialog = new DeleteDialog(this, R.style.customDialogStyle, this);
        dialog.show();
    }

    @Override
    public void confirm() {
        final LogEntry logEntry = mList.get(mPosition);
        Single.create(new SingleOnSubscribe<Integer>() {
            @Override
            public void subscribe(SingleEmitter<Integer> e) throws Exception {
                DBHelper dbHelper = new DBHelper(LogActivity.this);
                SQLiteDatabase database = dbHelper.getWritableDatabase();
                int delete = database.delete(DataContracts.LOGS.TABLE_NAME, "_id=?", new String[]{String.valueOf(logEntry.getId())});
                Integer integer = delete;
                e.onSuccess(integer);
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SingleObserver<Integer>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        mDeleteDisposable = d;
                    }

                    @Override
                    public void onSuccess(Integer value) {
                        Toast.makeText(LogActivity.this, "删除成功", Toast.LENGTH_SHORT).show();
                        if (mList.size() == 1) {
                            mList.clear();
                            mAdapter.notifyDataSetChanged();
                        } else {
                            mList.remove(mPosition);
                            mAdapter.notifyDataSetChanged();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Toast.makeText(LogActivity.this, "删除失败", Toast.LENGTH_SHORT).show();
                    }
                });
    }

//    private static class MyHandler extends Handler {
//
//        WeakReference<Activity> mWeakReference;
//
//        public MyHandler(Activity activity) {
//            mWeakReference = new WeakReference<Activity>(activity);
//        }
//
//        @Override
//        public void handleMessage(Message msg) {
//            final Activity activity = mWeakReference.get();
//            if(activity != null) {
//                switch (msg.what) {
//                    case LOAD_OK:
//                        if (msg.obj != null) {
//                            List<LogEntry> list = (ArrayList<LogEntry>) msg.obj;
//                            if (list.size() > 0) {
//                                if (activity instanceof LogActivity) {
//                                    LogActivity logActivity = (LogActivity) activity;
//                                    logActivity.mList.clear();
//                                    logActivity.mList.addAll(list);
//                                    logActivity.mAdapter.notifyDataSetChanged();
//                                }
//                            }
//                        }
//                        break;
//                }
//            }
//        }
//    }
}
